package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.utils.StringUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_agentDao;
import com.power.sifa.approve.dao.Apl_applicantDao;
import com.power.sifa.approve.model.Apl_agent;
import com.power.sifa.approve.model.Apl_applicant;
import com.power.sifa.approve.model.pageInfo.Apl_applicantPageInfo;
import com.power.sifa.approve.service.Apl_applicantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  申请人业务层实现
 */
@Service
public class Apl_applicantServiceImpl extends BaseServiceImpl implements Apl_applicantService {

    @Resource
    private Apl_applicantDao dao;
    @Resource
    private Apl_agentDao apl_agentDao;
    @Resource
    private Ha_attachmentService ha_attachmentService;

    @Override
    public Apl_applicant getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_applicant apl_applicant) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_applicant.getPrimaryKey() != null) {
        	 Apl_applicant apl_applicantfDb = dao.findById(apl_applicant.getPrimaryKey()).orElse(null);
             if(apl_applicantfDb != null) {
                BeanUtils.copyProperties(apl_applicant, apl_applicantfDb);
                dao.save(apl_applicantfDb);
                return;
             }
        }
        dao.save(apl_applicant);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_applicant> findAll(Apl_applicantPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        Page<Apl_applicant> page = dao.findAll(spec, pageable);
        // 新增查询附件的信息
        if (CollectionUtil.isEmpty(page.getContent())) {
            return page;
        }
        getAttachFile(page.getContent(), Apl_applicant::getFilecard, Boolean.FALSE);
        getAttachFile(page.getContent(), Apl_applicant::getDoccard, Boolean.TRUE);
        return dao.findAll(spec, pageable);
    }


    public void getAttachFile(List<Apl_applicant> applicantList, Function<Apl_applicant, String> function,
                              Boolean isDoc) {
        if (ObjectUtil.isNotNull(applicantList) && CollectionUtil.isNotEmpty(applicantList)) {
            Map<String, List<String>> attchMap = new HashMap<>();
            List<String> attchId = new ArrayList<>();
            applicantList.stream().forEach(item -> {
                String attchid = function.apply(item);
                if (StringUtils.isNotEmpty(attchid)) {
                    List<String> attchList = Arrays.asList(attchid.split(","));
                    attchId.addAll(attchList);
                    attchMap.put(item.getId(), attchList);
                }
            });
            // 查询对应的附件数据
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attchId);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                for (String id : attchMap.keySet()) {
                    List<Ha_attachment> fileLists = new ArrayList<>();
                    List<String> attchids = attchMap.get(id);
                    for (String attchid : attchids) {
                        if (ObjectUtil.isNotNull(ha_attachmentMap.get(attchid))) {
                            fileLists.add(ha_attachmentMap.get(attchid));
                        }
                    }
                    applicantList.stream().filter(item -> item.getId().equals(id)).findFirst().ifPresent(obj -> {
                        if (isDoc) {
                            obj.setDoccardList(fileLists);
                        } else {
                            obj.setFilecardList(fileLists);
                        }
                    });
                }
            }
        }

    }



    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Apl_applicant> findAll() {
		return dao.findAll();
	}

	@Override
	public void saveAll(List<Apl_applicant> list) {
		dao.saveAll(list);
	}

    @Override
    public List<Map<String, Object>> getAppperAndThiperByApplyid(String applyid) {
        return this.dao.getAppperAndThiperByApplyid(applyid);
    }

    @Override
    public List<Apl_applicant> getApplicantByApplyid(String applyid) {
        Specification<Apl_applicant> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("applyid"), applyid)
        ).getRestriction();
        return dao.findAll(specification);
    }

    @Override
    public Map<Integer, List<Apl_applicant>> getApplicantWithGroup(String applyid) {
        List<Apl_applicant> applicantList  = this.getApplicantByApplyid(applyid);
        if (CollectionUtil.isEmpty(applicantList)) {
            return null;
        }
        getAttachFile(applicantList, Apl_applicant::getFilecard, Boolean.FALSE);
        getAttachFile(applicantList, Apl_applicant::getDoccard, Boolean.TRUE);
        return applicantList.stream().collect(Collectors.groupingBy(Apl_applicant::getType));
    }

    /**
     * 申请人名称查询
     * @param name
     * @return
     */
    @Override
    public List<Apl_applicant> searchByName(String name) {
        List<Map<String, Object>> cardNoList = dao.searchCardNoByName("%" + name + "%");
        if (CollectionUtil.isNotEmpty(cardNoList)) {
            // 按照名称去重
            Map<String, String> distictMap = new HashMap<>();
            for (Map<String,Object> cardMap: cardNoList) {
               String cardNo = (String) cardMap.get("cardNo");
               String id = (String) cardMap.get("id");
               distictMap.put(cardNo, id);
            }
            List<String> ids = new ArrayList<>();
            for (String key : distictMap.keySet()) {
                String id = distictMap.get(key).toString();
                ids.add(id);
            }
            return dao.getByIds(ids);
        }
        return Collections.emptyList();
    }

    @Override
    public List<Apl_applicant> getApplicantAndAgent(String applyid) {
        List<Apl_applicant> applicantList = this.dao.getByApplyid(applyid);
        if(CollectionUtils.isEmpty(applicantList)) {
            return null;
        }
        List<Apl_agent> agentList = this.apl_agentDao.getByApplyid(applyid);
        if(!CollectionUtils.isEmpty(agentList)) {
            // 组装代理人map
            Map<String, List<Apl_agent>> tempMap = new HashMap<>(16);
            List<Apl_agent> tempList;
            for (Apl_agent apl_agent : agentList) {
                if(!StringUtil.isEmpty(apl_agent.getApplicantname())) {
                    String[] appIds = apl_agent.getApplicantname().split(",");
                    for (String id : appIds) {
                        if(null == tempMap.get(id)) {
                            tempList = new ArrayList<>(10);
                        } else {
                            tempList = tempMap.get(id);
                        }
                        tempList.add(apl_agent);
                        tempMap.put(id, tempList);
                    }
                }
            }
            // 把代理人放入被申请人列表中
            for (Apl_applicant apl_applicant : applicantList) {
                if(null != tempMap.get(apl_applicant.getId())) {
                    apl_applicant.setAgentList(tempMap.get(apl_applicant.getId()));
                }
            }
        }
        return applicantList;
    }

    @Override
    public PageDataResponse getCardnoPendingList(Apl_applicantPageInfo pageInfo) {
        List<Apl_applicant> list = this.dao.getCardnoPendingList(pageInfo);

        //分页
        PageDataResponse page = new PageDataResponse();
        if(CollectionUtil.isNotEmpty(list)){
            for(Apl_applicant data : list){
                data.geneText();
            }
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if(total.intValue() - size > 0){
                page.setNextPage((pageInfo.getPageNumber()) + 1);
            }
            page.setSize(pageInfo.getPageNumber() + 1);
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        }else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public PageDataResponse getCardnoProcessedList(Apl_applicantPageInfo pageInfo) {
        List<Apl_applicant> list = this.dao.getCardnoProcessedList(pageInfo);

        //分页
        PageDataResponse page = new PageDataResponse();
        if(CollectionUtil.isNotEmpty(list)){
            for(Apl_applicant data : list){
                data.geneText();
            }
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if(total.intValue() - size > 0){
                page.setNextPage((pageInfo.getPageNumber()) + 1);
            }
            page.setSize(pageInfo.getPageNumber() + 1);
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        }else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }


}
